package com.redsoil.house.utils;

import com.weidingqiang.rxfiflibrary2.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * 作者：weidingqiang on 2017/9/26 20:46
 * 邮箱：dqwei@iflytek.com
 */

public class RxTimerUtil {

    private static Disposable mDisposable;

    /** milliseconds毫秒后执行next操作
    *
    * @param milliseconds
    * @param next
    */
    public static void timer(long milliseconds,final IRxNext next) {
        Observable.timer(milliseconds, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable=disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if(next!=null){
                            next.doNext(number);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //取消订阅
                        cancel();
                    }

                    @Override
                    public void onComplete() {
                        //取消订阅
                        cancel();
                    }
            });
    }

    /** 每隔milliseconds毫秒后执行next操作
        *
        * @param milliseconds
        * @param next
        */
    public static void interval(long milliseconds,final IRxNext next){

            Observable.interval(milliseconds, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable disposable) {
                            mDisposable=disposable;
                        }

                        @Override
                        public void onNext(@NonNull Long number) {
                            if(next!=null){
                                next.doNext(number);
                            }
                        }
                        @Override
                        public void onError(@NonNull Throwable e) {

                        }
                        @Override
                        public void onComplete() {

                        }
                    });
    }
    /**
        * 取消订阅
        */
    public static void cancel(){

        if(mDisposable!=null&&!mDisposable.isDisposed()){
            mDisposable.dispose();
            LogUtil.debug("","====定时器取消======");
        }
    }


    public interface IRxNext{
        void doNext(long number);
    }
}
